home *** CD-ROM | disk | FTP | other *** search
/ MacTech 1 to 12 / MacTech-vol-1-12.toast / Reference / FAQs on CD / C++ FAQ Lite (3⁄7) < prev    next >
Encoding:
Text File  |  1997-01-17  |  54.5 KB  |  1,566 lines  |  [TEXT/R*ch]

  1. Archive-name: C++-faq/part3
  2. Posting-Frequency: monthly
  3. Last-modified: Jan 1, 1997
  4. URL: http://www.cerfnet.com/~mpcline/c++-faq-lite/
  5.  
  6. AUTHOR: Marshall Cline / cline@parashift.com / Paradigm Shift, Inc. /
  7. One Park St. / Norwood, NY 13668 / 315-353-6100 (voice) / 315-353-6110 (fax)
  8.  
  9. COPYRIGHT: This posting is part of "C++ FAQ Lite."  The entire "C++ FAQ Lite"
  10. document is Copyright(C) 1991-96 Marshall P. Cline, Ph.D., cline@parashift.com.
  11. All rights reserved.  Copying is permitted only under designated situations.
  12. For details, see section [1].
  13.  
  14. NO WARRANTY: THIS WORK IS PROVIDED ON AN "AS IS" BASIS.  THE AUTHOR PROVIDES NO
  15. WARRANTY WHATSOEVER, EITHER EXPRESS OR IMPLIED, REGARDING THE WORK, INCLUDING
  16. WARRANTIES WITH RESPECT TO ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
  17. PURPOSE.
  18.  
  19. C++-FAQ-Lite != C++-FAQ-Book: This document, C++ FAQ Lite, is not the same as
  20. the C++ FAQ Book.  The book (C++ FAQs, Cline and Lomow, Addison-Wesley) is 500%
  21. larger than this document, and is available in bookstores.  For details, see
  22. section [3].
  23.  
  24. ==============================================================================
  25.  
  26. SECTION [7]: Classes and objects
  27.  
  28.  
  29. [7.1] What is a class?
  30.  
  31. The fundamental building block of OO software.
  32.  
  33. A class defines a data type, much like a struct would be in C.  In a computer
  34. science sense, a type consists of both a set of states and a set of operations
  35. which transition between those states.  Thus int is a type because it has both
  36. a set of states and it has operations like i + j or i++, etc.  In exactly the
  37. same way, a class provides a set of (usually public:) operations, and a set of
  38. (usually non-public:) data bits representing the abstract values that instances
  39. of the type can have.
  40.  
  41. Think of int as a class that has member functions called operator++, etc.
  42.  
  43. Note: a C programmer can think of a class as a C struct whose members default
  44. to private.  But if that's all you think of a class, then you probably need to
  45. experience a personal paradigm shift.
  46.  
  47. ==============================================================================
  48.  
  49. [7.2] What is an object?
  50.  
  51. A region of storage with associated semantics.
  52.  
  53. After the declaration int i; we say that "i is an object of type int." In
  54. OO/C++, "object" usually means "an instance of a class." Thus a class defines
  55. the behavior of possibly many objects (instances).
  56.  
  57. ==============================================================================
  58.  
  59. [7.3] When is an interface "good"?
  60.  
  61. When it provides a simplified view of a chunk of software, and it is expressed
  62. in the vocabulary of a user (where a "chunk" is normally a class or a tight
  63. group of classes[14.2], and a "user" is another developer rather than the
  64. ultimate customer).
  65.  * The "simplified view" means unnecessary details are intentionally hidden.
  66.    This reduces the user's defect-rate.
  67.  * The "vocabulary of users" means users don't need to learn a new set of words
  68.    and concepts.  This reduces the user's learning curve.
  69.  
  70. ==============================================================================
  71.  
  72. [7.4] What is encapsulation?
  73.  
  74. Preventing unauthorized access to some piece of information or functionality.
  75.  
  76. The key money-saving insight is to separate the volatile part of some chunk of
  77. software from the stable part.  Encapsulation puts a firewall around the chunk,
  78. which prevents other chunks from accessing the volatile parts; other chunks can
  79. only access the stable parts.  This prevents the other chunks from breaking if
  80. (when!) the volatile parts are changed.  In context of OO software, a "chunk"
  81. is normally a class or a tight group of classes[14.2].
  82.  
  83. The "volatile parts" are the implementation details.  If the chunk is a single
  84. class, the volatile part is normally encapsulated using the private: and/or
  85. protected: keywords[19.5].  If the chunk is a tight group of classes[14.2],
  86. encapsulation can be used to deny access to entire classes in that group.
  87. Inheritance[19] can also be used as a form of encapsulation[22.2].
  88.  
  89. The "stable parts" are the interfaces.  A good interface provides a simplified
  90. view in the vocabulary of a user[7.3], and is designed from the
  91. outside-in[13.9] (here a "user" means another developer, not the end-user who
  92. buys the completed application).  If the chunk is a single class, the interface
  93. is simply the class's public: member functions and friend[14] functions.  If
  94. the chunk is a tight group of classes[14.2], the interface can include several
  95. of the classes in the chunk.
  96.  
  97. Designing a clean interface and separating that interface from its
  98. implementation[22.1] merely allows users to use the interface.  But
  99. encapsulating (putting "in a capsule") the implementation forces users to use
  100. the interface.
  101.  
  102. ==============================================================================
  103.  
  104. [7.5] How does C++ help with the tradeoff of safety vs. usability?
  105.  
  106. In C, encapsulation[7.4] was accomplished by making things static in a
  107. compilation unit or module.  This prevented another module from accessing the
  108. static stuff.  (By the way, that use is now depreciated: don't do that in C++.)
  109.  
  110. Unfortunately this approach doesn't support multiple instances of the data,
  111. since there is no direct support for making multiple instances of a module's
  112. static data.  If multiple instances were needed in C, programmers typically
  113. used a struct.  But unfortunately C structs don't support encapsulation[7.4].
  114. This exacerbates the tradeoff between safety (information hiding) and usability
  115. (multiple instances).
  116.  
  117. In C++, you can have both multiple instances and encapsulation via a class.
  118. The public: part of a class contains the class's interface, which normally
  119. consists of the class's public: member functions and its friend[14] functions.
  120. The private: and/or protected:[19.5] parts of a class contain the class's
  121. implementation, which is typically where the data lives.
  122.  
  123. The end result is like an "encapsulated struct." This reduces the tradeoff
  124. between safety (information hiding) and usability (multiple instances).
  125.  
  126. ==============================================================================
  127.  
  128. [7.6] How can I prevent other programmers from violating encapsulation by
  129.       seeing the private parts of my class?
  130.  
  131. Not worth the effort -- encapsulation is for code, not people.
  132.  
  133. It doesn't violate encapsulation for a programmer to see the private: and/or
  134. protected:[19.5] parts of your class, so long as they don't write code that
  135. somehow depends on what they saw.  In other words, encapsulation doesn't
  136. prevent people from knowing about the inside of a class; it prevents the code
  137. they write from becoming dependent on the insides of the class.  Your company
  138. doesn't have to pay a "maintenance cost" to maintain the gray matter between
  139. your ears; but it does have to pay a maintenance cost to maintain the code that
  140. comes out of your finger tips.  What you know as a person doesn't increase
  141. maintenance cost, provided the code they write depends on the interface rather
  142. than the implementation.
  143.  
  144. Besides, this is rarely if ever a problem.  I don't know any programmers who
  145. have intentionally tried to accessed the private parts of a class.  "My
  146. recommendation in such cases would be to change the programmer, not the code"
  147. [James Kanze, kanze@gabi-soft.fr; used with permission].
  148.  
  149. ==============================================================================
  150.  
  151. [7.7] Is Encapsulation a Security device?
  152.  
  153. No.
  154.  
  155. Encapsulation != security.
  156.  
  157. Encapsulation prevents mistakes, not espionage.
  158.  
  159. ==============================================================================
  160.  
  161. [7.8] What's the difference between the keywords struct and class?
  162.  
  163. The members and base classes of a struct are public by default, while in class,
  164. they default to private.  Note: you should make your base classes explicitly
  165. public, private, or protected, rather than relying on the defaults.
  166.  
  167. struct and class are otherwise functionally equivalent.
  168.  
  169. OK, enough of that squeaky clean techno talk.  Emotionally, most developers
  170. make a strong distinction between a class and a struct.  A struct simply feels
  171. like an open pile of bits with very little in the way of encapsulation or
  172. functionality.  A class feels like a living and responsible member of society
  173. with intelligent services, a strong encapsulation barrier, and a well defined
  174. interface.  Since that's the connotation most people already have, you should
  175. probably use the struct keyword if you have a class that has very few methods
  176. and has public data (such things do exist in well designed systems!), but
  177. otherwise you should probably use the class keyword.
  178.  
  179. ==============================================================================
  180.  
  181. SECTION [8]: References
  182.  
  183.  
  184. [8.1] What is a reference?
  185.  
  186. An alias (an alternate name) for an object.
  187.  
  188. References are frequently used for pass-by-reference:
  189.  
  190.     void swap(int& i, int& j)
  191.     {
  192.       int tmp = i;
  193.       i = j;
  194.       j = tmp;
  195.     }
  196.  
  197.     main()
  198.     {
  199.       int x, y;
  200.       // ...
  201.       swap(x,y);
  202.     }
  203.  
  204. Here i and j are aliases for main's x and y respectively.  In other words, i is
  205. x -- not a pointer to x, nor a copy of x, but x itself.  Anything you do to i
  206. gets done to x, and vice versa.
  207.  
  208. OK.  That's how you should think of references as a programmer.  Now, at the
  209. risk of confusing you by giving you a different perspective, here's how
  210. references are implemented.  Underneath it all, a reference i to object x is
  211. typically the machine address of the object x.  But when the programmer says
  212. i++, the compiler generates code that increments x.  In particular, the address
  213. bits that the compiler uses to find x are not changed.  A C programmer will
  214. think of this as if you used the C style pass-by-pointer, with the syntactic
  215. variant of (1) moving the & from the caller into the callee, and (2)
  216. eliminating the *s.  In other words, a C programmer will think of i as a macro
  217. for (*p), where p is a pointer to x (e.g., the compiler automatically
  218. dereferences the underlying pointer; i++ is changed to (*p)++; i = 7 is
  219. automatically changed to *p = 7).
  220.  
  221. Important note: Even though a reference is often implemented using an address
  222. in the underlying assembly language, please do not think of a reference as a
  223. funny looking pointer to an object.  A reference is the object.  It is not a
  224. pointer to the object, nor a copy of the object.  It is the object.
  225.  
  226. ==============================================================================
  227.  
  228. [8.2] What happens if you assign to a reference?
  229.  
  230. You change the referent (the object to which the reference refers).
  231.  
  232. Remember: the reference is the referent, so changing the reference changes the
  233. referent.  In compiler writer lingo, a reference is an "lvalue" (something that
  234. can appear on the left hand side of an assignment operator).
  235.  
  236. ==============================================================================
  237.  
  238. [8.3] What happens if you return a reference?
  239.  
  240. The function call can appear on the left hand side of an assignment operator.
  241.  
  242. This ability may seem strange at first.  For example, no one thinks the
  243. expression f() = 7 makes sense.  Yet, if a is an object of class Array, most
  244. people think that a[i] = 7 makes sense even though a[i] is really just a
  245. function call in disguise (it calls Array::operator[](int), which is the
  246. subscript operator for class Array).
  247.  
  248.     class Array {
  249.     public:
  250.       int size() const;
  251.       float& operator[] (int index);
  252.       // ...
  253.     };
  254.  
  255.     main()
  256.     {
  257.       Array a;
  258.       for (int i = 0; i < a.size(); ++i)
  259.         a[i] = 7;    // This line invokes Array::operator[](int)
  260.     }
  261.  
  262. ==============================================================================
  263.  
  264. [8.4] How can you reseat a reference to make it refer to a different object?
  265.       [UPDATED!]
  266.  
  267. [Recently changed last line from "pointer to const" to "const pointer" thanks
  268. to Neelesh Pandit (on 11/96).]
  269.  
  270. No way.
  271.  
  272. You can't separate the reference from the referent.
  273.  
  274. Unlike a pointer, once a reference is bound to an object, it can not be
  275. "reseated" to another object.  The reference itself isn't an object (it has no
  276. identity; taking the address of a reference gives you the address of the
  277. referent; remember: the reference is its referent).
  278.  
  279. In that sense, a reference is similar to a const pointer[18.5] such as
  280. int* const p (as opposed to a pointer to const[18.4] such as const int* p).  In
  281. spite of the gross similarity, please don't confuse references with pointers;
  282. they're not at all the same.
  283.  
  284. ==============================================================================
  285.  
  286. [8.5] When should I use references, and when should I use pointers?
  287.  
  288. Use references when you can, and pointers when you have to.
  289.  
  290. References are usually preferred over pointers whenever you don't need
  291. "reseating"[8.4].  This usually means that references are most useful in a
  292. class's public interface.  References typically appear on the skin of an
  293. object, and pointers on the inside.
  294.  
  295. The exception to the above is where a function's parameter or return value
  296. needs a "sentinel" reference.  This is usually best done by returning/taking a
  297. pointer, and giving the NULL pointer this special significance (references
  298. should always alias objects, not a dereferenced NULL pointer).
  299.  
  300. Note: Old line C programmers sometimes don't like references since they provide
  301. reference semantics that isn't explicit in the caller's code.  After some C++
  302. experience, however, one quickly realizes this is a form of information hiding,
  303. which is an asset rather than a liability.  E.g., programmers should write code
  304. in the language of the problem rather than the language of the machine.
  305.  
  306. ==============================================================================
  307.  
  308. SECTION [9]: Inline functions
  309.  
  310.  
  311. [9.1] What's the deal with inline functions?
  312.  
  313. An inline function is a function whose code gets inserted into the caller's
  314. code stream.  Like a #define macro, inline functions improve performance by
  315. avoiding the overhead of the call itself and (especially!) by the compiler
  316. being able to optimize through the call ("procedural integration").
  317.  
  318. ==============================================================================
  319.  
  320. [9.2] How can inline functions help with the tradeoff of safety vs. speed?
  321.  
  322. In straight C, you can achieve "encapsulated structs" by putting a void* in a
  323. struct, in which case the void* points to the real data that is unknown to
  324. users of the struct.  Therefore users of the struct don't know how to interpret
  325. the stuff pointed to by the void*, but the access functions cast the void* to
  326. the approprate hidden type.  This gives a form of encapsulation.
  327.  
  328. Unfortunately it forfeits type safety, and also imposes a function call to
  329. access even trivial fields of the struct (if you allowed direct access to the
  330. struct's fields, anyone and everyone would be able to get direct access since
  331. they would of necessity know how to interpret the stuff pointed to by the
  332. void*; this would make it difficult to change the underlying data structure).
  333.  
  334. Function call overhead is small, but can add up.  C++ classes allow function
  335. calls to be expanded inline.  This lets you have the safety of encapsulation
  336. along with the speed of direct access.  Furthermore the parameter types of
  337. these inline functions are checked by the compiler, an improvement over C's
  338. #define macros.
  339.  
  340. ==============================================================================
  341.  
  342. [9.3] Why should I use inline functions? Why not just use plain old #define
  343.       macros?
  344.  
  345. Because #define macros are evil.
  346.  
  347. Unlike #define macros, inline functions avoid infamous macro errors since
  348. inline functions always evaluate every argument exactly once.  In other words,
  349. invoking an inline function is semantically just like invoking a regular
  350. function, only faster:
  351.  
  352.     // A macro that returns the absolute value of i
  353.     #define unsafe(i)  \
  354.             ( (i) >= 0 ? (i) : -(i) )
  355.  
  356.     // An inline function that returns the absolute value of i
  357.     inline
  358.     int safe(int i)
  359.     {
  360.       return i >= 0 ? i : -i;
  361.     }
  362.  
  363.     int f();
  364.  
  365.     void userCode(int x)
  366.     {
  367.       int ans;
  368.  
  369.       ans = unsafe(x++);   // Error! x is incremented twice
  370.       ans = unsafe(f());   // Danger! f() is called twice
  371.  
  372.       ans = safe(x++);     // Correct! x is incremented once
  373.       ans = safe(f());     // Correct! f() is called once
  374.     }
  375.  
  376. Also unlike macros, argument types are checked, and necessary conversions are
  377. performed correctly.
  378.  
  379. Macros are bad for your health; don't use them unless you have to.
  380.  
  381. ==============================================================================
  382.  
  383. [9.4] How do you tell the compiler to make a non-member function inline?
  384.  
  385. When you declare an inline function, it looks just like a normal function:
  386.  
  387.     void f(int i, char c);
  388.  
  389. But when you define an inline function, you prepend the function's definition
  390. with the keyword inline, and you put the definition into a header file:
  391.  
  392.     inline
  393.     void f(int i, char c)
  394.     {
  395.       // ...
  396.     }
  397.  
  398. Note: It's imperative that the function's definition (the part between the
  399. {...}) be placed in a header file, unless the function is used only in a single
  400. .cpp file.  In particular, if you put the inline function's definition into a
  401. .cpp file and you call it from some other .cpp file, you'll get an "unresolved
  402. external" error from the linker.
  403.  
  404. ==============================================================================
  405.  
  406. [9.5] How do you tell the compiler to make a member function inline?
  407.  
  408. When you declare an inline member function, it looks just like a normal member
  409. function:
  410.  
  411.     class Fred {
  412.     public:
  413.       void f(int i, char c);
  414.     };
  415.  
  416. But when you define an inline member function, you prepend the member
  417. function's definition with the keyword inline, and you put the definition into
  418. a header file:
  419.  
  420.     inline
  421.     void Fred::f(int i, char c)
  422.     {
  423.       // ...
  424.     }
  425.  
  426. It's usually imperative that the function's definition (the part between the
  427. {...}) be placed in a header file.  If you put the inline function's definition
  428. into a .cpp file, and if it is called from some other .cpp file, you'll get an
  429. "unresolved external" error from the linker.
  430.  
  431. ==============================================================================
  432.  
  433. [9.6] Is there another way to tell the compiler to make a member function
  434.       inline?
  435.  
  436. Yep: define the member function in the class body itself:
  437.  
  438.     class Fred {
  439.     public:
  440.       void f(int i, char c)
  441.         {
  442.           // ...
  443.         }
  444.     };
  445.  
  446. Although this is easier on the person who writes the class, it's harder on all
  447. the readers since it mixes "what" a class does with "how" it does them.
  448. Because of this mixture, we normally prefer to define member functions outside
  449. the class body with the inline keyword[9.5].  The insight that makes sense of
  450. this: in a reuse-oriented world, there will usually be many people who use your
  451. class, but there is only one person who builds it (yourself); therefore you
  452. should do things that favor the many rather than the few.
  453.  
  454. ==============================================================================
  455.  
  456. [9.7] Are inline functions guaranteed to make your performance better?
  457.  
  458. Nope.
  459.  
  460. Beware that overuse of inline functions can cause code bloat, which can in turn
  461. have a negative performance impact in paging environments.
  462.  
  463. ==============================================================================
  464.  
  465. SECTION [10]: Constructors
  466.  
  467.  
  468. [10.1] What's the deal with constructors?
  469.  
  470. Constructors build objects from dust.
  471.  
  472. Constructors are like "init functions".  They turn a pile of arbitrary bits
  473. into a living object.  Minimally they initialize internally used fields.  They
  474. may also allocate resources (memory, files, semaphores, sockets, etc).
  475.  
  476. "ctor" is a typical abbreviation for constructor.
  477.  
  478. ==============================================================================
  479.  
  480. [10.2] Is there any difference between List x; and List x();?
  481.  
  482. A big difference!
  483.  
  484. Suppose that List is the name of some class.  Then function f() declares a
  485. local List object called x:
  486.  
  487.     void f()
  488.     {
  489.       List x;     // Local object named x (of class List)
  490.       // ...
  491.     }
  492.  
  493. But function g() declares a function called x() that returns a List:
  494.  
  495.     void g()
  496.     {
  497.       List x();   // Function named x (that returns a List)
  498.       // ...
  499.     }
  500.  
  501. ==============================================================================
  502.  
  503. [10.3] How can I make a constructor call another constructor as a primitive?
  504.  
  505. No way.
  506.  
  507. Dragons be here: if you call another constructor, the compiler initializes a
  508. temporary local object; it does not initialize this object.  You can combine
  509. both constructors by using a default parameter, or you can share their common
  510. code in a private init() member function.
  511.  
  512. ==============================================================================
  513.  
  514. [10.4] Is the default constructor for Fred always Fred::Fred()?
  515.  
  516. No.  A "default constructor" is a constructor that can be called with no
  517. arguments.  Thus a constructor that takes no arguments is certainly a default
  518. constructor:
  519.  
  520.     class Fred {
  521.     public:
  522.       Fred();   // Default constructor: can be called with no args
  523.       // ...
  524.     };
  525.  
  526. However it is possible (and even likely) that a default constructor can take
  527. arguments, provided they are given default values:
  528.  
  529.     class Fred {
  530.     public:
  531.       Fred(int i=3, int j=5);   // Default constructor: can be called with no args
  532.       // ...
  533.     };
  534.  
  535. ==============================================================================
  536.  
  537. [10.5] Which constructor gets called when I create an array of Fred objects?
  538.  
  539. Fred's default constructor[10.4].
  540.  
  541. There is no way to tell the compiler to call a different constructor.  If your
  542. class Fred doesn't have a default constructor[10.4], attempting to create an
  543. array of Fred objects is trapped as an error at compile time.
  544.  
  545.     class Fred {
  546.     public:
  547.       Fred(int i, int j);
  548.       // ... assume there is no default constructor[10.4] in class Fred ...
  549.     };
  550.  
  551.     main()
  552.     {
  553.       Fred a[10];               // ERROR: Fred doesn't have a default constructor
  554.       Fred* p = new Fred[10];   // ERROR: Fred doesn't have a default constructor
  555.     }
  556.  
  557. However if you are creating an STL[32.1] vector<Fred> rather than an array of
  558. Fred (which you probably should be doing anyway since arrays are evil[21.5]),
  559. you don't have to have a default constructor in class Fred, since you can give
  560. the vector a Fred object to be used to initialize the elements:
  561.  
  562.     #include <vector>
  563.     using namespace std;
  564.  
  565.     main()
  566.     {
  567.       vector<Fred> a(10, Fred(5,7));
  568.       // The 10 Fred objects in vector a will be initialized with Fred(5,7).
  569.       // ...
  570.     }
  571.  
  572. ==============================================================================
  573.  
  574. [10.6] What is the "Named Constructor Idiom"?
  575.  
  576. A technique that provides more intuitive and/or safer construction operations
  577. for users of your class.
  578.  
  579. The problem is that constructors always have the same name as the class.
  580. Therefore the only way to differentiate between the various constructors of a
  581. class is by the parameter list.  But if there are lots of constructors, the
  582. differences between the constructors becomes somewhat subtle and error prone.
  583.  
  584. With the Named Constructor Idiom, you declare all the class's constructors in
  585. the private: or protected: sections, and you provide public static methods that
  586. return an object.  These static methods are the so-called "Named Constructors."
  587. In general there is one such static method for each different way to construct
  588. an object.
  589.  
  590. For example, suppose we are building a Point class that represents a position
  591. on the X-Y plane.  Turns out there are two common ways to specify a 2-space
  592. coordinate: rectangular coordinates (X+Y), polar coordinates (Radius+Angle).
  593. (Don't worry if you can't remember these; the point isn't the particulars of
  594. coordinate systems; the point is that there are several ways to create a Point
  595. object).  Unfortunately the parameters for these two coordinate systems are the
  596. same: two floats.  This would create an ambiguity error in the overloaded
  597. constructors:
  598.  
  599.     class Point {
  600.     public:
  601.       Point(float x, float y);     // Rectangular coordinates
  602.       Point(float r, float a);     // Polar coordinates (radius and angle)
  603.       // ERROR: Overload is Ambiguous: Point::Point(float,float)
  604.     };
  605.  
  606.     main()
  607.     {
  608.       Point p = Point(5.7, 1.2);   // Ambiguous: Which coordinate system?
  609.     }
  610.  
  611. One way to solve this ambiguity is to use the Named Constructor Idiom:
  612.  
  613.     #include <math.h>              // To get sin() and cos()
  614.  
  615.     class Point {
  616.     public:
  617.       static Point rectangular(float x, float y);      // Rectangular coord's
  618.       static Point polar(float radius, float angle);   // Polar coordinates
  619.       // These static methods are the so-called "named constructors"
  620.       // ...
  621.     private:
  622.       Point(float x, float y);     // Rectangular coordinates
  623.       float x_, y_;
  624.     };
  625.  
  626.     inline Point::Point(float x, float y)
  627.     : x_(x), y_(y) { }
  628.  
  629.     inline Point Point::rectangular(float x, float y)
  630.     { return Point(x, y); }
  631.  
  632.     inline Point Point::polar(float radius, float angle)
  633.     { return Point(radius*cos(angle), radius*sin(angle)); }
  634.  
  635. Now the users of Point have a clear and unambiguous syntax for creating Points
  636. in either coordinate system:
  637.  
  638.     main()
  639.     {
  640.       Point p1 = Point::rectangular(5.7, 1.2);   // Obviously rectangular
  641.       Point p2 = Point::polar(5.7, 1.2);         // Obviously polar
  642.     }
  643.  
  644. Make sure your constructors are in the protected: section if you expect Fred to
  645. have derived classes.
  646.  
  647. The Named Constructor Idiom can also be used to make sure your objects are
  648. always created via new[16.18].
  649.  
  650. ==============================================================================
  651.  
  652. [10.7] Why can't I initialize my static member data in my constructor's
  653.        initialization list?
  654.  
  655. Because you must explicitly define your class's static data members.
  656.  
  657. Fred.h:
  658.  
  659.     class Fred {
  660.     public:
  661.       Fred();
  662.       // ...
  663.     private:
  664.       int i_;
  665.       static int j_;
  666.     };
  667.  
  668. Fred.cpp (or Fred.C or whatever):
  669.  
  670.     Fred::Fred()
  671.       : i_(10)  // OK: you can (and should) initialize member data this way
  672.         j_(42)  // Error: you cannot initialize static member data like this
  673.     {
  674.       // ...
  675.     }
  676.  
  677.     // You must define static data members this way:
  678.     int Fred::j_ = 42;
  679.  
  680. ==============================================================================
  681.  
  682. [10.8] Why are classes with static data members getting linker errors?
  683.  
  684. Because static data members must be explicitly defined in exactly one
  685. compilation unit[10.7].  If you didn't do this, you'll probably get an
  686. "undefined external" linker error.  For example:
  687.  
  688.     // Fred.h
  689.  
  690.     class Fred {
  691.     public:
  692.       // ...
  693.     private:
  694.       static int j_;   // Declares static data member Fred::j_
  695.       // ...
  696.     };
  697.  
  698. The linker will holler at you ("Fred::j_ is not defined") unless you define (as
  699. opposed to merely declare) Fred::j_ in (exactly) one of your source files:
  700.  
  701.     // Fred.cpp
  702.  
  703.     #include "Fred.h"
  704.  
  705.     int Fred::j_ = some_expression_evaluating_to_an_int;
  706.  
  707.     // Alternatively, if you wish to use the implicit 0 value for static ints:
  708.     // int Fred::j_;
  709.  
  710. The usual place to define static data members of class Fred is file Fred.cpp
  711. (or Fred.C or whatever source file extension you use).
  712.  
  713. ==============================================================================
  714.  
  715. SECTION [11]: Destructors
  716.  
  717.  
  718. [11.1] What's the deal with destructors?
  719.  
  720. A destructor gives an object its last rites.
  721.  
  722. Destructors are used to release any resources allocated by the object.  E.g.,
  723. class Lock might lock a semaphore, and the destructor will release that
  724. semaphore.  The most common example is when the constructor uses new, and the
  725. destructor uses delete.
  726.  
  727. Destructors are a "prepare to die" member function.  They are often abbreviated
  728. "dtor".
  729.  
  730. ==============================================================================
  731.  
  732. [11.2] What's the order that local objects are destructed?
  733.  
  734. In reverse order of construction: First constructed, last destructed.
  735.  
  736. In the following example, b's destructor will be executed first, then a's
  737. destructor:
  738.  
  739.     void userCode()
  740.     {
  741.       Fred a;
  742.       Fred b;
  743.       // ...
  744.     }
  745.  
  746. ==============================================================================
  747.  
  748. [11.3] What's the order that objects in an array are destructed?
  749.  
  750. In reverse order of construction: First constructed, last destructed.
  751.  
  752. In the following example, the order for destructors will be a[9], a[8], ...,
  753. a[1], a[0]:
  754.  
  755.     void userCode()
  756.     {
  757.       Fred a[10];
  758.       // ...
  759.     }
  760.  
  761. ==============================================================================
  762.  
  763. [11.4] Can I overload the destructor for my class?
  764.  
  765. No.
  766.  
  767. You can have only one destructor for a class Fred.  It's always called
  768. Fred::~Fred().  It never takes any parameters, and it never returns anything.
  769.  
  770. You can't pass parameters to the destructor anyway, since you never explicitly
  771. call a destructor[11.5] (well, almost never[11.10]).
  772.  
  773. ==============================================================================
  774.  
  775. [11.5] Should I explicitly call a destructor on a local variable?
  776.  
  777. No!
  778.  
  779. The destructor will get called again at the close } of the block in which the
  780. local was created.  This is a guarantee of the language; it happens
  781. automagically; there's no way to stop it from happening.  But you can get
  782. really bad results from calling a destructor on the same object a second time!
  783. Bang! You're dead!
  784.  
  785. ==============================================================================
  786.  
  787. [11.6] What if I want a local to "die" before the close } of the scope in which
  788.        it was created? Can I call a destructor on a local if I really want to?
  789.  
  790. No! [For context, please read the previous FAQ[11.5]].
  791.  
  792. Suppose the (desirable) side effect of destructing a local File object is to
  793. close the File.  Now suppose you have an object f of a class File and you want
  794. File f to be closed before the end of the scope (i.e., the }) of the scope of
  795. object f:
  796.  
  797.     void someCode()
  798.     {
  799.       File f;
  800.  
  801.       // ... [This code that should execute when f is still open] ...
  802.  
  803.       // <-- We want the side-effect of f's destructor here!
  804.  
  805.       // ... [This code that should execute after f is closed] ...
  806.     }
  807.  
  808. There is a simple solution to this problem[11.7].  But in the mean time,
  809. remember: Do not explicitly call the destructor![11.5]
  810.  
  811. ==============================================================================
  812.  
  813. [11.7] OK, OK already; I won't explicitly call the destructor of a local; but
  814.        how do I handle the above situation?
  815.  
  816. [For context, please read the previous FAQ[11.6]].
  817.  
  818. Simply wrap the extent of the lifetime of the local in an artificial block {
  819. ... }:
  820.  
  821.     void someCode()
  822.     {
  823.       {
  824.         File f;
  825.         // ... [This code will execute when f is still open] ...
  826.       }
  827.     // ^-- f's destructor will automagically be called here!
  828.  
  829.       // ... [This code will execute after f is closed] ...
  830.     }
  831.  
  832. ==============================================================================
  833.  
  834. [11.8] What if I can't wrap the local in an artificial block?
  835.  
  836. Most of the time, you can limit the lifetime of a local by wrapping the local
  837. in an artificial block ({ ...  })[11.7].  But if for some reason you can't do
  838. that, add a member function that has a similar effect as the destructor.  But
  839. do not call the destructor itself!
  840.  
  841. For example, in the case of class File, you might add a close() method.
  842. Typically the destructor will simply call this close() method.  Note that the
  843. close() method will need to mark the File object so a subsequent call won't
  844. re-close an already-closed File.  E.g., it might set the fileHandle_ data
  845. member to some nonsensical value such as -1, and it might check at the
  846. beginning to see if the fileHandle_ is already equal to -1:
  847.  
  848.     class File {
  849.     public:
  850.       void close();
  851.       ~File();
  852.       // ...
  853.     private:
  854.       int fileHandle_;   // fileHandle_ >= 0 if/only-if it's open
  855.     };
  856.  
  857.     File::~File()
  858.     {
  859.       close();
  860.     }
  861.  
  862.     void File::close()
  863.     {
  864.       if (fileHandle_ >= 0) {
  865.         // ... [Perform some operating-system call to close the file] ...
  866.         fileHandle_ = -1;
  867.       }
  868.     }
  869.  
  870. Note that the other File methods may also need to check if the fileHandle_ is
  871. -1 (i.e., check if the File is closed).
  872.  
  873. ==============================================================================
  874.  
  875. [11.9] But can I explicitly call a destructor if I've allocated my object with
  876.        new?
  877.  
  878. Probably not.
  879.  
  880. Unless you used placement new[11.10], you should simply delete the object
  881. rather than explicitly calling the destructor.  For example, suppose you
  882. allocated the object via a typical new expression:
  883.  
  884.     Fred* p = new Fred();
  885.  
  886. Then the destructor Fred::~Fred() will automagically get called when you delete
  887. it via:
  888.  
  889.     delete p;  // Automagically calls p->~Fred()
  890.  
  891. You should not explicitly call the destructor, since doing so won't release the
  892. memory that was allocated for the Fred object itself.  Remember: delete p does
  893. two things[16.8]: it calls the destructor and it deallocates the memory.
  894.  
  895. ==============================================================================
  896.  
  897. [11.10] What is "placement new" and why would I use it?
  898.  
  899. There are many uses of placement new.  The simplest use is to place an object
  900. at a particular location in memory.  This is done by supplying the place as a
  901. pointer parameter to the new part of a new expression:
  902.  
  903.     #include <new.h>      // Must #include this to use "placement new"
  904.     #include "Fred.h"     // Declaration of class Fred
  905.  
  906.     void someCode()
  907.     {
  908.       char memory[sizeof(Fred)];     // Line #1
  909.       void* place = memory;          // Line #2
  910.  
  911.       Fred* f = new(place) Fred();   // Line #3 (see "DANGER" below)
  912.       // The pointers f and place will be equal
  913.  
  914.       // ...
  915.     }
  916.  
  917. Line #1 creates an array of sizeof(Fred) bytes of memory, which is big enough
  918. to hold a Fred object.  Line #2 creates a pointer place that points to the
  919. first byte of this memory (experienced C programmers will note that this step
  920. was unnecessary; it's there only to make the code more obvious).  Line #3
  921. essentially just calls the constructor Fred::Fred().  The this pointer in the
  922. Fred constructor will be equal to place.  The returned pointer f will therefore
  923. be equal to place.
  924.  
  925. ADVICE: Don't use this "placement new" syntax unless you have to.  Use it only
  926. when you really care that an object is placed at a particular location in
  927. memory.  For example, when your hardware has a memory-mapped I/O timer device,
  928. and you want to place a Clock object at that memory location.
  929.  
  930. DANGER: You are taking sole responsibility that the pointer you pass to the
  931. "placement new" operator points to a region of memory that is big enough and is
  932. properly aligned for the object type that you're creating.  Neither the
  933. compiler nor the run-time system make any attempt to check whether you did this
  934. right.  If your Fred class needs to be aligned on a 4 byte boundary but you
  935. supplied a location that isn't properly aligned, you can have a serious
  936. disaster on your hands (if you don't know what "alignment" means, please don't
  937. use the placement new syntax).  You have been warned.
  938.  
  939. You are also solely responsible for destructing the placed object.  This is
  940. done by explicitly calling the destructor:
  941.  
  942.     void someCode()
  943.     {
  944.       char memory[sizeof(Fred)];
  945.       void* p = memory;
  946.       Fred* f = new(p) Fred();
  947.       // ...
  948.       f->~Fred();   // Explicitly call the destructor for the placed object
  949.     }
  950.  
  951. This is about the only time you ever explicitly call a destructor.
  952.  
  953. ==============================================================================
  954.  
  955. [11.11] When I write a destructor, do I need to explicitly call the destructors
  956.         for my member objects?
  957.  
  958. No.  You never need to explicitly call a destructor (except with placement
  959. new[11.10]).
  960.  
  961. A class's destructor (whether or not you explicitly define one) automagically
  962. invokes the destructors for member objects.  They are destroyed in the reverse
  963. order they appear within the declaration for the class.
  964.  
  965.     class Member {
  966.     public:
  967.       ~Member();
  968.       // ...
  969.     };
  970.  
  971.     class Fred {
  972.     public:
  973.       ~Fred();
  974.       // ...
  975.     private:
  976.       Member x_;
  977.       Member y_;
  978.       Member z_;
  979.     };
  980.  
  981.     Fred::~Fred()
  982.     {
  983.       // Compiler automagically calls z_.~Member()
  984.       // Compiler automagically calls y_.~Member()
  985.       // Compiler automagically calls x_.~Member()
  986.     }
  987.  
  988. ==============================================================================
  989.  
  990. [11.12] When I write a derived class's destructor, do I need to explicitly call
  991.         the destructor for my base class?
  992.  
  993. No.  You never need to explicitly call a destructor (except with placement
  994. new[11.10]).
  995.  
  996. A derived class's destructor (whether or not you explicitly define one)
  997. automagically invokes the destructors for base class subobjects.  Base classes
  998. are destructed after member objects.  In the event of multiple inheritance,
  999. direct base classes are destructed in the reverse order of their appearance in
  1000. the inheritance list.
  1001.  
  1002.     class Member {
  1003.     public:
  1004.       ~Member();
  1005.       // ...
  1006.     };
  1007.  
  1008.     class Base {
  1009.     public:
  1010.       virtual ~Base();     // A virtual destructor[20.4]
  1011.       // ...
  1012.     };
  1013.  
  1014.     class Derived : public Base {
  1015.     public:
  1016.       ~Derived();
  1017.       // ...
  1018.     private:
  1019.       Member x_;
  1020.     };
  1021.  
  1022.     Derived::~Derived()
  1023.     {
  1024.       // Compiler automagically calls x_.~Member()
  1025.       // Compiler automagically calls Base::~Base()
  1026.     }
  1027.  
  1028. Note: Order dependencies with virtual inheritance are trickier.  If you are
  1029. relying on order dependencies in a virtual inheritance hierarchy, you'll need a
  1030. lot more information than is in this FAQ.
  1031.  
  1032. ==============================================================================
  1033.  
  1034. SECTION [12]: Assignment operators
  1035.  
  1036.  
  1037. [12.1] What is "self assignment"?
  1038.  
  1039. Self assignment is when someone assigns an object with itself.  For example,
  1040.  
  1041.     #include "Fred.hpp"    // Declares class Fred
  1042.  
  1043.     void userCode(Fred& x)
  1044.     {
  1045.       x = x;   // Self-assignment
  1046.     }
  1047.  
  1048. Obviously no one ever explicitly does a self assignment like the above, but
  1049. since more than one pointer or reference can point to the same object
  1050. (aliasing), it is possible to have self assignment without knowning it:
  1051.  
  1052.     #include "Fred.hpp"    // Declares class Fred
  1053.  
  1054.     void userCode(Fred& x, Fred& y)
  1055.     {
  1056.       x = y;   // Could be self-assignment if &x == &y
  1057.     }
  1058.  
  1059.     main()
  1060.     {
  1061.       Fred z;
  1062.       userCode(z, z);
  1063.     }
  1064.  
  1065. ==============================================================================
  1066.  
  1067. [12.2] Why should I worry about "self assignment"?
  1068.  
  1069. If you don't worry about self assignment[12.1], you'll expose your users to
  1070. some very subtle bugs that have very subtle and often disastrous symptoms.  For
  1071. example, the following class will cause a complete disaster in the case of
  1072. self-assignment:
  1073.  
  1074.     class Wilma { };
  1075.  
  1076.     class Fred {
  1077.     public:
  1078.       Fred()                : p_(new Wilma())      { }
  1079.       Fred(const Fred& f)   : p_(new Wilma(*f.p_)) { }
  1080.      ~Fred()                { delete p_; }
  1081.       Fred& operator= (const Fred& f)
  1082.         {
  1083.           // Bad code: Doesn't handle self-assignment!
  1084.           delete p_;                // Line #1
  1085.           p_ = new Wilma(*f.p_);    // Line #2
  1086.           return *this;
  1087.         }
  1088.     private:
  1089.       Wilma* p_;
  1090.     };
  1091.  
  1092. If someone assigns a Fred object with itself, line #1 deletes both this->p_ and
  1093. f.p_ since *this and f are the same object.  But line #2 uses *f.p_, which is
  1094. no longer a valid object.  This will likely cause a major disaster.
  1095.  
  1096. The bottom line is that you the author of class Fred are responsible to make
  1097. sure self-assignment on a Fred object is inocuous[12.3].  Do not assume that
  1098. users won't ever do that to your objects.  It is your fault if your object
  1099. crashes when it gets a self-assignment.
  1100.  
  1101. Aside: the above Fred::operator= (const Fred&) has a second problem:     If an
  1102. exception is thrown[17] while evaluating new Wilma(*f.p_) (e.g., an
  1103. out-of-memory     exception[16.5] or an exception in Wilma's copy
  1104.     constructor[17.1]), this->p_ will be a dangling pointer -- it will
  1105.     point to memory that is no longer valid.  This can be solved by allocating
  1106. the     new objects before deleting the old objects.
  1107.  
  1108. ==============================================================================
  1109.  
  1110. [12.3] OK, OK, already; I'll handle self-assignment.  How do I do it?
  1111.  
  1112. You should worry about self assignment every time you create a class[12.2].
  1113. This does not mean that you need to add extra code to all your classes: as long
  1114. as your objects gracefully handle self assignment, it doesn't matter whether
  1115. you had to add extra code or not.
  1116.  
  1117. If you do need to add extra code to your assignment operator, here's a simple
  1118. and effective technique:
  1119.  
  1120.     Fred& Fred::operator= (const Fred& f)
  1121.     {
  1122.       if (this == &f) return *this;   // Gracefully handle self assignment[12.1]
  1123.  
  1124.       // Put the normal assignment duties here...
  1125.  
  1126.       return *this;
  1127.     }
  1128.  
  1129. This explicit test isn't always necessary.  For example, if you were to fix the
  1130. assignment operator in the previous FAQ[12.2] to handle exceptions thrown by
  1131. new[16.5] and/or exceptions thrown by the copy constructor[17.1] of class
  1132. Wilma, you might produce the following code.  Note that this code has the
  1133. (pleasant) side effect of automatically handling self assignment as well:
  1134.  
  1135.     Fred& operator= (const Fred& f)
  1136.     {
  1137.       // This code gracefully (albeit implicitly) handles self assignment[12.1]
  1138.       Wilma* tmp = new Wilma(*f.p_);   // It would be OK if an exception[17] got thrown here
  1139.       delete p_;
  1140.       p_ = tmp;
  1141.       return *this;
  1142.     }
  1143.  
  1144. Some programmers want to add "if (this == &f) return *this;" to make self
  1145. assignment more efficient.  This is generally the wrong tradeoff.  If self
  1146. assignment only occurs once in a thousand times, the if would waste cycles in
  1147. 99.9% of the time (a test-and-branch can put a bubble in the pipeline of many
  1148. superscalar processors).
  1149.  
  1150. ==============================================================================
  1151.  
  1152. SECTION [13]: Operator overloading
  1153.  
  1154.  
  1155. [13.1] What's the deal with operator overloading?
  1156.  
  1157. It allows you to provide an intuitive interface to users of your class.
  1158.  
  1159. Operator overloading allows C/C++ operators to have user-defined meanings on
  1160. user-defined types (classes).  Overloaded operators are syntactic sugar for
  1161. function calls:
  1162.  
  1163.     class Fred {
  1164.     public:
  1165.       // ...
  1166.     };
  1167.  
  1168.     #if 0
  1169.  
  1170.       // Without operator overloading:
  1171.       Fred add(Fred, Fred);
  1172.       Fred mul(Fred, Fred);
  1173.  
  1174.       Fred f(Fred a, Fred b, Fred c)
  1175.       {
  1176.         return add(add(mul(a,b), mul(b,c)), mul(c,a));    // Yuk...
  1177.       }
  1178.  
  1179.     #else
  1180.  
  1181.       // With operator overloading:
  1182.       Fred operator+ (Fred, Fred);
  1183.       Fred operator* (Fred, Fred);
  1184.  
  1185.       Fred f(Fred a, Fred b, Fred c)
  1186.       {
  1187.         return a*b + b*c + c*a;
  1188.       }
  1189.  
  1190.     #endif
  1191.  
  1192. ==============================================================================
  1193.  
  1194. [13.2] What are the benefits of operator overloading?
  1195.  
  1196. By overloading standard operators on a class, you can exploit the intuition of
  1197. the users of that class.  This lets users program in the language of the
  1198. problem domain rather than in the language of the machine.
  1199.  
  1200. The ultimate goal is to reduce both the learning curve and the defect rate.
  1201.  
  1202. ==============================================================================
  1203.  
  1204. [13.3] What are some examples of operator overloading?
  1205.  
  1206. Here are a few of the many examples of operator overloading:
  1207.  * myString + yourString might concatenate two string objects
  1208.  * myDate++ might increment a Date object
  1209.  * a * b might multiply two Number objects
  1210.  * a[i] might access an element of an Array object
  1211.  * x = *p might dereference a "smart pointer" that actually "points" to a disk
  1212.    record -- it could actually seek to the location on disk where p "points"
  1213.    and return the appropriate record into x
  1214.  
  1215. ==============================================================================
  1216.  
  1217. [13.4] But operator overloading makes my class look ugly; isn't it supposed to
  1218.        make my code clearer?
  1219.  
  1220. Operator overloading makes life easier for the users of a class[13.2], not for
  1221. the developer of the class!
  1222.  
  1223. Consider the following example.
  1224.  
  1225.     class Array {
  1226.     public:
  1227.       int& operator[] (unsigned i);      // Some people don't like this syntax
  1228.       // ...
  1229.     };
  1230.  
  1231.     inline
  1232.     int& Array::operator[] (unsigned i)  // Some people don't like this syntax
  1233.     {
  1234.       // ...
  1235.     }
  1236.  
  1237. Some people don't like the keyword operator or the somewhat funny syntax that
  1238. goes with it in the body of the class itself.  But the operator overloading
  1239. syntax isn't supposed to make life easier for the developer of a class.  It's
  1240. supposed to make life easier for the users of the class:
  1241.  
  1242.     main()
  1243.     {
  1244.       Array a;
  1245.       a[3] = 4;   // User code should be obvious and easy to understand...
  1246.     }
  1247.  
  1248. Remember: in a reuse-oriented world, there will usually be many people who use
  1249. your class, but there is only one person who builds it (yourself); therefore
  1250. you should do things that favor the many rather than the few.
  1251.  
  1252. ==============================================================================
  1253.  
  1254. [13.5] What operators can/cannot be overloaded?
  1255.  
  1256. Most can be overloaded. The only C operators that can't be are . and ?: (and
  1257. sizeof, which is technically an operator).  C++ adds a few of its own
  1258. operators, most of which can be overloaded except :: and .*.
  1259.  
  1260. Here's an example of the subscript operator (it returns a reference).  First
  1261. without operator overloading:
  1262.  
  1263.     class Array {
  1264.     public:
  1265.       #if 0
  1266.         int& elem(unsigned i)        { if (i > 99) error(); return data[i]; }
  1267.       #else
  1268.         int& operator[] (unsigned i) { if (i > 99) error(); return data[i]; }
  1269.       #endif
  1270.     private:
  1271.       int data[100];
  1272.     };
  1273.  
  1274.     main()
  1275.     {
  1276.       Array a;
  1277.  
  1278.       #if 0
  1279.         a.elem(10) = 42;
  1280.         a.elem(12) += a.elem(13);
  1281.       #else
  1282.         a[10] = 42;
  1283.         a[12] += a[13];
  1284.       #endif
  1285.     }
  1286.  
  1287. ==============================================================================
  1288.  
  1289. [13.6] Can I overload operator== so it lets me compare two char[] using a
  1290.        string comparison?
  1291.  
  1292. No: at least one operand of any overloaded operator must be of some class type.
  1293.  
  1294. But even if C++ allowed you to do this, which it doesn't, you wouldn't want to
  1295. do it anyway since you really should be using a string-like class rather than
  1296. an array of char in the first place[17.3] since arrays are evil[21.5].
  1297.  
  1298. ==============================================================================
  1299.  
  1300. [13.7] Can I create a operator** for "to-the-power-of" operations?
  1301.  
  1302. Nope.
  1303.  
  1304. The names of, precedence of, associativity of, and arity of operators is fixed
  1305. by the language.  There is no operator** in C++, so you cannot create one for a
  1306. class type.
  1307.  
  1308. If you're in doubt, consider that x ** y is the same as x * (*y) (in other
  1309. words, the compiler assumes y is a pointer).  Besides, operator overloading is
  1310. just syntactic sugar for function calls.  Although this particular syntactic
  1311. sugar can be very sweet, it doesn't add anything fundamental.  I suggest you
  1312. overload pow(base,exponent) (a double precision version is in <math.h>).
  1313.  
  1314. By the way, operator^ can work for to-the-power-of, except it has the wrong
  1315. precedence and associativity.
  1316.  
  1317. ==============================================================================
  1318.  
  1319. [13.8] How do I create a subscript operator for a Matrix class?
  1320.  
  1321. Use operator() rather than operator[].
  1322.  
  1323. When you have multiple subscripts, the cleanest way to do it is with operator()
  1324. rather than with operator[].  The reason is that operator[] always takes
  1325. exactly one parameter, but operator() can take any number of parameters (in the
  1326. case of a rectangular matrix, two paramters are needed).
  1327.  
  1328. For example:
  1329.  
  1330.     class Matrix {
  1331.     public:
  1332.       Matrix(unsigned rows, unsigned cols);
  1333.       double& operator() (unsigned row, unsigned col);
  1334.       double  operator() (unsigned row, unsigned col) const;
  1335.       // ...
  1336.      ~Matrix();                              // Destructor
  1337.       Matrix(const Matrix& m);               // Copy constructor
  1338.       Matrix& operator= (const Matrix& m);   // Assignment operator
  1339.       // ...
  1340.     private:
  1341.       unsigned rows_, cols_;
  1342.       double* data_;
  1343.     };
  1344.  
  1345.     inline
  1346.     Matrix::Matrix(unsigned rows, unsigned cols)
  1347.       : rows_ (rows),
  1348.         cols_ (cols),
  1349.         data_ (new double[rows * cols])
  1350.     {
  1351.       if (rows == 0 || cols == 0)
  1352.         throw BadIndex("Matrix constructor has 0 size");
  1353.     }
  1354.  
  1355.     inline
  1356.     Matrix::~Matrix()
  1357.     {
  1358.       delete[] data_;
  1359.     }
  1360.  
  1361.     inline
  1362.     double& Matrix::operator() (unsigned row, unsigned col)
  1363.     {
  1364.       if (row >= rows_ || col >= cols_)
  1365.         throw BadIndex("Matrix subscript out of bounds");
  1366.       return data_[cols_*row + col];
  1367.     }
  1368.  
  1369.     inline
  1370.     double Matrix::operator() (unsigned row, unsigned col) const
  1371.     {
  1372.       if (row >= rows_ || col >= cols_)
  1373.         throw BadIndex("const Matrix subscript out of bounds");
  1374.       return data_[cols_*row + col];
  1375.     }
  1376.  
  1377. Then you can access an element of Matrix m using m(i,j) rather than m[i][j]:
  1378.  
  1379.     main()
  1380.     {
  1381.       Matrix m;
  1382.       m(5,8) = 106.15;
  1383.       cout << m(5,8);
  1384.       // ...
  1385.     }
  1386.  
  1387. ==============================================================================
  1388.  
  1389. [13.9] Should I design my classes from the outside (interfaces first) or from
  1390.        the inside (data first)?
  1391.  
  1392. From the outside!
  1393.  
  1394. A good interface provides a simplified view that is expressed in the vocabulary
  1395. of a user[7.3].  In the case of OO software, the interface is normally to a
  1396. class or a tight group of classes[14.2].
  1397.  
  1398. First think about what the object logically represents, not how you intend to
  1399. physically build it.  For example, suppose you have a Stack class that will be
  1400. built by containing a LinkedList:
  1401.  
  1402.     class Stack {
  1403.     public:
  1404.       // ...
  1405.     private:
  1406.       LinkedList list_;
  1407.     };
  1408.  
  1409. Should the Stack have a get() method that returns the LinkedList? Or a set()
  1410. method that takes a LinkedList? Or a constructor that takes a LinkedList?
  1411. Obviously the answer is No, since you should design your interfaces from the
  1412. outside-in.  I.e., users of Stack objects don't care about LinkedLists; they
  1413. care about pushing and popping.
  1414.  
  1415. Now for another example that is a bit more subtle.  Suppose class LinkedList is
  1416. built using a linked list of Node objects, where each Node object has a pointer
  1417. to the next Node:
  1418.  
  1419.     class Node { /*...*/ };
  1420.  
  1421.     class LinkedList {
  1422.     public:
  1423.       // ...
  1424.     private:
  1425.       Node* first_;
  1426.     };
  1427.  
  1428. Should the LinkedList class have a get() method that will let users access the
  1429. first Node? Should the Node object have a get() method that will let users
  1430. follow that Node to the next Node in the chain? In other words, what should a
  1431. LinkedList look like from the outside? Is a LinkedList really a chain of Node
  1432. objects? Or is that just an implementation detail? And if it is just an
  1433. implementation detail, how will the LinkedList let users access each of the
  1434. elements in the LinkedList one at a time?
  1435.  
  1436. One man's answer: A LinkedList is not a chain of Nodes.  That may be how it is
  1437. built, but that is not what it is.  What it is is a sequence of elements.
  1438. Therefore the LinkedList abstraction should provide a "LinkedListIterator"
  1439. class as well, and that "LinkedListIterator" might have an operator++ to go to
  1440. the next element, and it might have a get()/set() pair to access its value
  1441. stored in the Node (the value in the Node element is solely the responsibility
  1442. of the LinkedList user, which is why there is a get()/set() pair that allows
  1443. the user to freely manipulate that value).
  1444.  
  1445. Starting from the user's perspective, we might want our LinkedList class to
  1446. support operations that look similar to accessing an array using pointer
  1447. arithmetic:
  1448.  
  1449.     void userCode(LinkedList& a)
  1450.     {
  1451.       for (LinkedListIterator p = a.begin(); p != a.end(); ++p)
  1452.         cout << *p << '\n';
  1453.     }
  1454.  
  1455. To implement this interface, LinkedList will need a begin() method and an end()
  1456. method.  These return a "LinkedListIterator" object.  The "LinkedListIterator"
  1457. will need a method to go forward, ++p; a method to access the current element,
  1458. *p; and a comparison operator, p != a.end().
  1459.  
  1460. The code follows.  The key insight is that the LinkedList class does not have
  1461. any methods that lets users access the Nodes.  Nodes are an implementation
  1462. technique that is completely buried.  The LinkedList class could have its
  1463. internals replaced with a doubly linked list, or even an array, and the only
  1464. difference would be some performance differences with the prepend(elem) and
  1465. append(elem) methods.
  1466.  
  1467.     #include <assert.h>   // Poor man's exception handling
  1468.  
  1469.     typedef  int  bool;   // Someday we won't have to do this
  1470.  
  1471.     class LinkedListIterator;
  1472.     class LinkedList;
  1473.  
  1474.     class Node {
  1475.       // No public members; this is a "private class"
  1476.       friend LinkedListIterator;   // A friend class[14]
  1477.       friend LinkedList;
  1478.       Node* next_;
  1479.       int elem_;
  1480.     };
  1481.  
  1482.     class LinkedListIterator {
  1483.     public:
  1484.       bool operator== (LinkedListIterator i) const;
  1485.       bool operator!= (LinkedListIterator i) const;
  1486.       void operator++ ();   // Go to the next element
  1487.       int& operator*  ();   // Access the current element
  1488.     private:
  1489.       LinkedListIterator(Node* p);
  1490.       Node* p_;
  1491.     };
  1492.  
  1493.     class LinkedList {
  1494.     public:
  1495.       void append(int elem);    // Adds elem after the end
  1496.       void prepend(int elem);   // Adds elem before the beginning
  1497.       // ...
  1498.       LinkedListIterator begin();
  1499.       LinkedListIterator end();
  1500.       // ...
  1501.     private:
  1502.       Node* first_;
  1503.     };
  1504.  
  1505. Here are the methods that are obviously inlinable (probably in the same header
  1506. file):
  1507.  
  1508.     inline bool LinkedListIterator::operator== (LinkedListIterator i) const
  1509.     {
  1510.       return p_ == i.p_;
  1511.     }
  1512.  
  1513.     inline bool LinkedListIterator::operator!= (LinkedListIterator i) const
  1514.     {
  1515.       return p_ != i.p_;
  1516.     }
  1517.  
  1518.     inline void LinkedListIterator::operator++()
  1519.     {
  1520.       assert(p_ != NULL);  // or if (p_==NULL) throw ...
  1521.       p_ = p_->next_;
  1522.     }
  1523.  
  1524.     inline int& LinkedListIterator::operator*()
  1525.     {
  1526.       assert(p_ != NULL);  // or if (p_==NULL) throw ...
  1527.       return p_->elem_;
  1528.     }
  1529.  
  1530.     inline LinkedListIterator::LinkedListIterator(Node* p)
  1531.       : p_(p)
  1532.     { }
  1533.  
  1534.     inline LinkedListIterator LinkedList::begin()
  1535.     {
  1536.       return first_;
  1537.     }
  1538.  
  1539.     inline LinkedListIterator LinkedList::end()
  1540.     {
  1541.       return NULL;
  1542.     }
  1543.  
  1544. Conclusion: The linked list had two different kinds of data.  The values of the
  1545. elements stored in the linked list are the responsibility of the user of the
  1546. linked list (and only the user; the linked list itself makes no attempt to
  1547. prohibit users from changing the third element to 5), and the linked list's
  1548. infrastructure data (next pointers, etc.), whose values are the responsibility
  1549. of the linked list (and only the linked list; e.g., the linked list does not
  1550. let users change (or even look at!) the various next pointers).
  1551.  
  1552. Thus the only get()/set() methods were to get and set the elements of the
  1553. linked list, but not the infrastructure of the linked list.  Since the linked
  1554. list hides the infrastructure pointers/etc., it is able to make very strong
  1555. promises regarding that infrastructure (e.g., if it was a doubly linked list,
  1556. it might guarantee that every forward pointer was matched by a backwards
  1557. pointer from the next Node).
  1558.  
  1559. So, we see here an example of where the values of some of a class's data is the
  1560. responsibility of users (in which case the class needs to have get()/set()
  1561. methods for that data) but the data that the class wants to control does not
  1562. necessarily have get()/set() methods.
  1563.  
  1564. ==============================================================================
  1565.  
  1566.